<?php
namespace App\Repository;

use App\Model\User;
use App\Repository\User\{Money, MoneyFull, MoneyDiscount, MoneyPay, MoneyWallet};

use App\Facade\Event;
use App\Event\User\CreateEvent;

class UserRepository extends \HyperfStore\Repository
{
    use MoneyWallet, MoneyPay, MoneyDiscount, MoneyFull, Money;
    
    // 放入模型
    public function build()
    {
        return new User;
    }

    // 登陆
    public function login($data)
    {
        if($user = User::tokenLogin($data))
        {
            // 只允许一个 token
            $user->tokenFlush();
            
            return ['token' => $user->tokenCreate('user-token')];
        }
    }
    
    // 创建
    public function create($data)
    {
        $res = $this->exception(function() use($data) {
            return $this->save($data);
        });
        
        if($res)
        {
            Event::dispatch(new CreateEvent($this));
        }
        
        return $res;
    }
    
    // 更新用户
    public function update($data)
    {
        // 是否重置密码
        if(isset($data['password']) && !$data['password'])
        {
            unset($data['password']);
        }
        
        // 更新资料
        return $this->exception(function() use($data) {
            return $this->save($data);
        });
    }
    
    // 升级
    public function setLevel(LevelRepository $level)
    {
        $this->model->level()->associate($level->model());
        
        return $this->model->save();
    }
    
    // 绑定店铺
    public function setShop(ShopRepository $shop)
    {
        $this->model->shop()->associate($shop->model());
        
        return $this->model->save();
    }
    
    // 设置上级与关系链
    public function setUser(UserRepository $user)
    {
        $this->model->user()->associate($user->model());
        
        // 生成关系链
        $all = $user->user_all;
        $all[] = $user->id;
        
        $this->model->user_all = $all;
        
        return $this->model->save();
    }
}